var express = require('express'),
  basic = require('../../basicmodule/basic.js'),
  fs = require('fs'),
  router = express.Router();

var utils = require('../tool/Utils.js')

module.exports = function (app) {
  app.use('/', router);
};

var DIRPATH = 'freedom' + utils.format + 'upload' + utils.format;

router.get('/download.html', function (req, res, next) {
  var queryParam = req.query;
  if (queryParam != undefined) {

    // 实现文件下载
    var p = basic.getFilePath(DIRPATH);

    var filePath = p + queryParam.file_name;

    console.log("find file path:" + filePath);

    res.download(filePath);
  }

});


function walk(path, it) {
  var dirList = fs.readdirSync(path);
  console.log(dirList.length);
  for (var i = 0; i < dirList.length; i++) {
    var item = dirList[i];
    if (fs.statSync(path + '/' + item).isDirectory()) {
      if (item == it) {
        return path + '/' + item;
      } else {
        var j = walk(path + '/' + item, it);
        if (j) {
          return j;
        } else {
          continue;
        }
      }
    } else if (fs.statSync(path + '/' + item).isFile()) {
      if (item == it) {
        return path + '/' + item;
      }
    }
  }
};


router.post('/download.html', function (req, res) {
  var queryParam = req.body.file_name;

  if (queryParam != undefined) {
    res.download(basic.getFilePath(DIRPATH) + queryParam);
  }
});

router.get('/checkVersion.html', function (req, res, next) {

  var queryParam = req.query;
  if (queryParam != undefined) {

    DIRPATH = "freedom/upload/StreamingAssets" + queryParam.packageName + "/";

    fs.readFile(basic.getFilePath(DIRPATH) + "files.txt", 'utf-8', function (err, data) {

      if (err) {
        res.send(err);
      } else {
        res.send(data);
      }
    });
  }


});
